package com.freecloud.spring.advice;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.freecloud.spring.common.ResponseBody;
import com.freecloud.spring.controller.SimplController;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 拦截返回参数，在返回前过滤掉无权参数
 *
 * @Author: maomao
 * @Date: 2021-05-17 14:13
 */
@ControllerAdvice
public class AttributeFilterAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //获取当前处理请求的controller的方法
        String methodName = methodParameter.getMethod().getName();
        // 不拦截/不需要处理返回值 的方法
        String method = "login"; //如登录
        //不拦截
        return !method.equals(methodName);
    }

    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter, MediaType mediaType,
        Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //将返回值returnValue转成我需要的类型Message<?>  方便统一修改其中的某个属性
        // Messages是我自定义的一个类
        Object dataObj = ((ResponseBody)returnValue).getData();
        System.out.println(dataObj.getClass());

        System.out.println("befer : " + JSONUtil.toJsonStr(returnValue));

        SimplController.User newUser = (SimplController.User)dataObj;
        newUser.setName("new - 3333");

        System.out.println("after : " + JSONUtil.toJsonStr(returnValue));

        //过滤字段
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.addMixIn(SimplController.User.class, JsonIgnoreType.class);
        objectMapper.addMixIn(ResponseBody.class, JsonIgnoreType.class);

        //        FilterProvider filterProvider =
        //            new SimpleFilterProvider().addFilter("noneFilter", SimpleBeanPropertyFilter.serializeAllExcept("code"));

        FilterProvider filterProvider =
            new SimpleFilterProvider().addFilter("user", SimpleBeanPropertyFilter.filterOutAllExcept("code"));

        ObjectWriter writer = objectMapper.writer(filterProvider);

        try {
            System.out.println("filter attrbute : " + writer.writeValueAsString(returnValue));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        //返回修改后的值
        return returnValue;
    }
}
